package com.haierp.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.impl.client.BasicCookieStore;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gargoylesoftware.htmlunit.HttpMethod;
import com.haierp.enums.ItemStatus;
import com.haierp.enums.PlatformType;
import com.haierp.mapper.InventoryAreaMapper;
import com.haierp.mapper.InventoryMapper;
import com.haierp.mapper.ItemMapper;
import com.haierp.mapper.ItemSkuMapper;
import com.haierp.mapper.OuterItemMapper;
import com.haierp.mapper.OuterItemSkuMapper;
import com.haierp.model.Inventory;
import com.haierp.model.InventoryArea;
import com.haierp.model.Item;
import com.haierp.model.ItemSku;
import com.haierp.model.item.OuterItem;
import com.haierp.model.item.OuterItemSku;
import com.haierp.service.IInventoryService;
import com.haierp.service.IOneHaoCangService;
import com.haierp.util.DateUtil;
import com.haierp.util.SimpleHtmlUnitUtils;

import net.sf.ezmorph.bean.MorphDynaBean;
import net.sf.json.JSONObject;

@Service("oneHaoCangService")
public class OneHaoCangServiceImpl implements IOneHaoCangService {
    private Logger logger = LogManager.getLogger(getClass());
    
	@Autowired
	ItemMapper itemMapper;
	
	@Autowired
	ItemSkuMapper itemSkuMapper;
	
	@Autowired
	OuterItemMapper outerItemMapper;
	
	@Autowired
	OuterItemSkuMapper outerItemSkuMapper;
	
	@Autowired
	InventoryMapper inventoryMapper;
	
	@Autowired
	IInventoryService inventoryService;
	
	@Autowired
	InventoryAreaMapper inventoryAreaMapper;
	
	//同步1号仓的商品信息
	@Override
	public void synItemList() {
		//获取访问1号仓的cookie
		BasicCookieStore cookieStore = getOneHaoCangCookie("1hcangCookie.dat");
		
		//类目map
		//正式1号仓
		Map<String, Long> categoryIdMap = new HashMap<String, Long>();
		categoryIdMap.put("1fdfc406-255a-4337-9021-df5194892ab3", 46L);
		categoryIdMap.put("ff9c7c30-ec9f-472f-adf5-2ad5afe055ae", 48L);
		categoryIdMap.put("4f77525a-c430-435b-8de2-742681a7e15f", 50L);
		categoryIdMap.put("4c027ab5-dd46-4617-afc5-33d0a38659e6", 52L);
		Map<String, String> categoryNameMap = new HashMap<String, String>();
		categoryNameMap.put("1fdfc406-255a-4337-9021-df5194892ab3", "美妆护肤");
		categoryNameMap.put("ff9c7c30-ec9f-472f-adf5-2ad5afe055ae", "箱包皮具");
		categoryNameMap.put("4f77525a-c430-435b-8de2-742681a7e15f", "家庭日用");
		categoryNameMap.put("4c027ab5-dd46-4617-afc5-33d0a38659e6", "潮流服饰");
		/*
		Map<String, Long> categoryIdMap = new HashMap<String, Long>();
		categoryIdMap.put("bf20e1d3-78f6-40cd-bd49-4d08f37f5b99", 46L);
		categoryIdMap.put("14447293-0c98-4ec1-a0c9-04aa5d841aca", 48L);
		categoryIdMap.put("37cf4cc6-05e1-413a-8b27-5ef872e4ba2f", 50L);
		categoryIdMap.put("caff580d-09f4-496e-bd54-ba54f7abfa71", 52L);
		Map<String, String> categoryNameMap = new HashMap<String, String>();
		categoryNameMap.put("bf20e1d3-78f6-40cd-bd49-4d08f37f5b99", "美妆护肤");
		categoryNameMap.put("14447293-0c98-4ec1-a0c9-04aa5d841aca", "箱包皮具");
		categoryNameMap.put("37cf4cc6-05e1-413a-8b27-5ef872e4ba2f", "家庭日用");
		categoryNameMap.put("caff580d-09f4-496e-bd54-ba54f7abfa71", "潮流服饰");
		*/
		Map<String, Integer> saleTypeMap = new HashMap<String, Integer>();
		saleTypeMap.put("TOBUY", 0);
		saleTypeMap.put("STORE", 1);
		Map<String, Integer> countryMap = new HashMap<String, Integer>();
		countryMap.put("美国", 1);
		countryMap.put("德国", 2);
		countryMap.put("日本", 3);
		countryMap.put("澳洲", 4);
		Map<String, Integer> currencyMap = new HashMap<String, Integer>();
		currencyMap.put("人民币", 1);
		currencyMap.put("美元", 2);
		Map<Boolean, Integer> yesOrNoMap = new HashMap<Boolean, Integer>();
		yesOrNoMap.put(false, 0);
		yesOrNoMap.put(true, 1);
		
		for(int pageNo=2; pageNo>=1; pageNo--) {
			System.out.println("===============================================pageNo：" + pageNo);
			int start = (pageNo-1)*20;
			String itemListJson = SimpleHtmlUnitUtils.httpRequest("http://erp.1hcang.com/ERP/Commodity/Search?page=" + pageNo + "&start=" + start + "&limit=20", HttpMethod.GET, null, null, cookieStore, "UTF-8");
			JSONObject itemListJsonObject = JSONObject.fromObject(itemListJson);
			Map<String, Object> itemListMap = (Map<String, Object>) JSONObject.toBean(itemListJsonObject, Map.class);
			List itemList = (ArrayList)itemListMap.get("data");
			Collections.reverse(itemList);
			for(int i=0; i<itemList.size(); i++) {
				String itemID = (String)((MorphDynaBean)itemList.get(i)).get("ID");
				System.out.println("===============================================itemID：" + itemID);
				try {
					String itemJson = SimpleHtmlUnitUtils.httpRequest("http://erp.1hcang.com/ERP/Commodity/GetItemByID?id=" + itemID, HttpMethod.GET, null, null, cookieStore, "UTF-8");
					JSONObject itemJsonObject = JSONObject.fromObject(itemJson);
					Map<String, Object> itemMap = (Map<String, Object>) JSONObject.toBean(itemJsonObject, Map.class);
					
					MorphDynaBean itemMorphDynaBean = (MorphDynaBean)itemMap.get("data");
					Item item = new Item();
					item.setName((String)itemMorphDynaBean.get("FullName"));							//商品全名
					item.setCategoryId(categoryIdMap.get((String)itemMorphDynaBean.get("TypeID")));		//类目id
					item.setCategoryName(categoryNameMap.get((String)itemMorphDynaBean.get("TypeID")));	//类目名称
					item.setItemCode((String)itemMorphDynaBean.get("SKU"));								//商品编码
					item.setIsNew(yesOrNoMap.get((Boolean)((MorphDynaBean)itemList.get(i)).get("IsNew")));	//是否新品
					item.setSaleType(saleTypeMap.get((String)itemMorphDynaBean.get("SellType")));		//销售类型
					item.setItemShort((String)itemMorphDynaBean.get("ShortName"));						//商品简称
					item.setEnName((String)itemMorphDynaBean.get("EnglishName"));						//英文名称
					item.setBrand((String)itemMorphDynaBean.get("Brand"));								//品牌
					item.setCountry(countryMap.get((String)itemMorphDynaBean.get("CountryName")));		//国家
					item.setCurrency(currencyMap.get((String)itemMorphDynaBean.get("CurrencyName")));	//币种
					item.setBuySite((String)itemMorphDynaBean.get("WebsiteName"));						//采购站点
					item.setOrigin((String)itemMorphDynaBean.get("Origin"));							//产地
					item.setWeight((Double)itemMorphDynaBean.get("Weight"));							//重量
					item.setUnit((String)itemMorphDynaBean.get("Unit"));								//单位
					item.setSource((String)itemMorphDynaBean.get("Source"));							//来源
					item.setPromotion((String)itemMorphDynaBean.get("DiscountInfo"));					//促销信息
					item.setContactPerson((String)itemMorphDynaBean.get("Contact"));					//联系人
					item.setContactTel((String)itemMorphDynaBean.get("ContactTel"));					//联系电话
					item.setIdCard(yesOrNoMap.get((Boolean)itemMorphDynaBean.get("LogisticsType")));		//是否身份证
					item.setStartDate(DateUtil.parseDate((String)itemMorphDynaBean.get("SellStartDate")));	//销售开始日期
					item.setEndDate(DateUtil.parseDate((String)itemMorphDynaBean.get("SellEndDate")));		//销售结束日期
					item.setStatus(ItemStatus.INIT.getCode());											//1号仓商品同步到系统的初始状态
					item.setRemark((String)itemMorphDynaBean.get("Remark"));								//商品备注
					item.setSpec((String)itemMorphDynaBean.get("Spec"));									//规格
					item.setModel((String)itemMorphDynaBean.get("Model"));									//型号
					item.setDetail(((String)itemMorphDynaBean.get("Description")).replaceAll("/UploadFiles", "http://erp.1hcang.com/UploadFiles"));	//商品详情
					
					//商品主图
					List imageList = (ArrayList)itemMorphDynaBean.get("ImageList");
					StringBuffer mainPic = new StringBuffer();
					mainPic.append("{\"picList\": [");
					int mainPicNum = 1;
					for(int j=0; j<imageList.size(); j++) {
						MorphDynaBean imgM = (MorphDynaBean)imageList.get(j);
						mainPic.append("{");
						mainPic.append("\"type\": \"" + (String)imgM.get("FileType") + "\",");
						mainPic.append("\"uid\": \"i_" + j + "\",");
						mainPic.append("\"url\": \"" + "http://erp.1hcang.com" + (String)imgM.get("FolderName") + (String)imgM.get("FileID") + (String)imgM.get("FileExtension") + "\"");
						if(j == (imageList.size()-1)) {
							mainPic.append("}");
						} else {
							mainPic.append("},");
						}
						if((boolean)imgM.get("IsMainPage")) {
							mainPicNum = j+1;
						}
					}
					mainPic.append("],\"mainPicNum\": \"" + mainPicNum + "\"}");
					item.setMainPic(mainPic.toString());
					item.setGmtModify(new Date());
					
					//如果商品存在就修改，不存在就添加
					Item tjItem = new Item();
					tjItem.setItemCode(item.getItemCode());
					Item selItem = itemMapper.selectOne(tjItem);
					if(selItem != null) {
						item.setId(selItem.getId());
						item.setStatus(selItem.getStatus());
						itemMapper.updateSelectiveById(item);
						/*
						//删除底下的sku
						ItemSku delItemSku = new ItemSku();
						delItemSku.setItemCode(item.getItemCode());
						itemSkuMapper.deleteSelective(delItemSku);
						*/
					} else {
						item.setGmtCreate(new Date());
						itemMapper.insertSelective(item);
					}
					
					//增加到outer_item表
					OuterItem outerItem = new OuterItem();
					outerItem.setItemId(item.getId());
					outerItem.setPlatformType(PlatformType.YOUZAN.getCode());
					outerItem.setOneItemId(itemID);
					OuterItem selOuterItem = outerItemMapper.selectOne(outerItem);
					if(selOuterItem == null) {
						outerItem.setStatus(ItemStatus.INIT.getCode());
						outerItemMapper.insert(outerItem);
					} else {
						outerItem.setId(selOuterItem.getId());
					}
					
					//======处理sku
					String itemSkuListJson = SimpleHtmlUnitUtils.httpRequest("http://erp.1hcang.com/ERP/CommodityItem/Search?page=1&start=0&limit=200&wildcard=" + item.getItemCode(), HttpMethod.GET, null, null, cookieStore, "UTF-8");
					JSONObject itemSkuListJsonObject = JSONObject.fromObject(itemSkuListJson);
					Map<String, Object> itemSkuListMap = (Map<String, Object>) JSONObject.toBean(itemSkuListJsonObject, Map.class);
					List itemSkuList = (ArrayList)itemSkuListMap.get("data");
					for(int k=0; k<itemSkuList.size(); k++) {
						MorphDynaBean itemSkuMorphDynaBean = (MorphDynaBean)itemSkuList.get(k);
						ItemSku itemSku = new ItemSku();
						itemSku.setItemId(item.getId());
						itemSku.setItemName(item.getName());
						itemSku.setCategoryId(item.getCategoryId());
						itemSku.setCategoryName(item.getCategoryName());
						itemSku.setItemCode(item.getItemCode());
						itemSku.setSkuCode((String)itemSkuMorphDynaBean.get("SKU"));
						itemSku.setUpc((String)itemSkuMorphDynaBean.get("Barcode"));
						itemSku.setSalable(yesOrNoMap.get((Boolean)itemSkuMorphDynaBean.get("AllowSale")));
						itemSku.setColor((String)itemSkuMorphDynaBean.get("CommodityItemColor"));
						itemSku.setScale((String)itemSkuMorphDynaBean.get("CommodityItemSize"));
						itemSku.setPurchasePrice((Double)itemSkuMorphDynaBean.get("CostPrice"));
						itemSku.setFreight((long)((double)itemSkuMorphDynaBean.get("FreightPrice")*100));				//单位分
						itemSku.setSalePrice((Double)itemSkuMorphDynaBean.get("SalesPrice"));
						itemSku.setRemark((String)itemSkuMorphDynaBean.get("Remark"));
						itemSku.setGmtModify(new Date());
						itemSku.setSaleType(item.getSaleType());
						itemSku.setBrand(item.getBrand());
						itemSku.setWeight((Double)itemSkuMorphDynaBean.get("Weight"));
						
						if(itemSku.getFreight() > 0) {	//拼邮
							itemSku.setLogisticType(1);
							item.setLogisticType(1);
						} else {
							itemSku.setLogisticType(0);
						}
						
						//sku图片
						StringBuffer skuPic = new StringBuffer();
						skuPic.append("{\"picList\": [");
						skuPic.append("{");
						skuPic.append("\"type\": \"image/jpeg\",");
						skuPic.append("\"uid\": \"i_0\",");
						skuPic.append("\"url\": \"" + "http://erp.1hcang.com/UploadFiles/Resource/" + (String)itemSkuMorphDynaBean.get("MainImageUrl") + "\"");
						skuPic.append("}");
						skuPic.append("]}");
						itemSku.setSkuPic(skuPic.toString());
						
						//如果SKU存在就修改，不存在就添加
						ItemSku tjItemSku = new ItemSku();
						tjItemSku.setSkuCode(itemSku.getSkuCode());
						ItemSku selItemSku = itemSkuMapper.selectOne(tjItemSku);
						if(selItemSku != null) {
							itemSku.setId(selItemSku.getId());
							itemSkuMapper.updateSelectiveById(itemSku);
						} else {
							itemSku.setGmtCreate(new Date());
							itemSkuMapper.insert(itemSku);
						}
						//增加到outer_item_sku表
						OuterItemSku outerItemSku = new OuterItemSku();
						outerItemSku.setItemId(item.getId());
						outerItemSku.setSkuId(itemSku.getId());
						outerItemSku.setPlatformType(PlatformType.YOUZAN.getCode());
						outerItemSku.setOuterItemId(outerItem.getId());
						outerItemSku.setSkuCode(itemSku.getSkuCode());
						OuterItemSku selOuterItemSku = outerItemSkuMapper.selectOne(outerItemSku);
						if(selOuterItemSku == null) {
							outerItemSkuMapper.insert(outerItemSku);
						}
						//修改inventory表，主要修改虚拟库存
						Inventory inventory = new Inventory();
						inventory.setSkuId(itemSku.getId());
						inventory.setItemId(item.getId());
						inventory.setItemName(item.getName());
						inventory.setUpc(itemSku.getUpc());
						inventory.setSkuCode(itemSku.getSkuCode());
						Double virtualInv = (Double)itemSkuMorphDynaBean.get("StoreQty");
						if(virtualInv < 0) {
							inventory.setVirtualInv(0);
						} else {
							inventory.setVirtualInv(virtualInv.intValue());
						}
						inventory.setGmtModify(new Date());
						
						Inventory selInventory = inventoryService.queryInventoryBySkuId(itemSku.getItemId(), itemSku.getId());
						if(selInventory != null) {
							selInventory.setVirtualInv(inventory.getVirtualInv());
							inventoryMapper.updateSelectiveById(selInventory);
						} else {
							inventory.setGmtCreate(new Date());
							inventoryMapper.insert(inventory);
						}
					}
					
					//根据sku的邮费判断是否为拼邮
					if(item.getLogisticType()==null) {
						item.setLogisticType(0);	//直邮
					}
					itemMapper.updateSelectiveById(item);
				} catch(Exception e) {
					logger.error("======>Exception itemID：" + itemID + "，pageNo：" + pageNo, e);
				}
			}
		}
		
	}
	
	//同步1号仓商品的库存
	@Override
	public void synItemInventory() {
		//获取访问1号仓的cookie
		BasicCookieStore cookieStore = getOneHaoCangCookie("1hcangCookie.dat");
		int jishu = 0;
		for(int pageNo=1; pageNo<=25; pageNo++) {
			System.out.println("===============================================pageNo：" + pageNo);
			int start = (pageNo-1)*25;
			String itemInventoryJson = SimpleHtmlUnitUtils.httpRequest("http://erp.1hcang.com/ERP/Inventory/Search?page=" + pageNo + "&start=" + start + "&limit=25&sort=%5B%7B%22property%22%3A%22CreatedDate%22%2C%22direction%22%3A%22ASC%22%7D%5D", HttpMethod.GET, null, null, cookieStore, "UTF-8");
			JSONObject itemInventoryJsonObject = JSONObject.fromObject(itemInventoryJson);
			Map<String, Object> itemInventoryMap = (Map<String, Object>) JSONObject.toBean(itemInventoryJsonObject, Map.class);
			List itemInventoryList = (ArrayList)itemInventoryMap.get("data");
			for(int i=0; i<itemInventoryList.size(); i++) {
				jishu++;
				MorphDynaBean itemInventoryMorphDynaBean = (MorphDynaBean)itemInventoryList.get(i);
				
				String skuCode = (String)itemInventoryMorphDynaBean.get("CommoditySKU");
				ItemSku tjItemSku = new ItemSku();
				tjItemSku.setSkuCode(skuCode);
				ItemSku itemSku = itemSkuMapper.selectOne(tjItemSku);
				if(itemSku==null) {
					logger.error("skuCode===>" + skuCode);
					continue;
				}
				
				String positionNo = (String)itemInventoryMorphDynaBean.get("InventorySign");
				Long warehouseId = 1L;
				String warehouseName = "波特兰仓";
				if(positionNo.toUpperCase().equals("YT")) {
					warehouseId = 2L;
					warehouseName = "西雅图仓";
				} else if(positionNo.toUpperCase().equals("GN")) {
					warehouseId = 3L;
					warehouseName = "国内仓";
				}
				
				InventoryArea selInventoryArea = inventoryAreaMapper.getInventoryArea(itemSku.getItemId(), itemSku.getId(), warehouseId, positionNo);
				
				InventoryArea inventoryArea = new InventoryArea();
				inventoryArea.setSkuId(itemSku.getId());
				inventoryArea.setWarehouseId(warehouseId);
				inventoryArea.setPositionNo(positionNo);
				inventoryArea.setColor(itemSku.getColor());
				inventoryArea.setUpc(itemSku.getUpc());
				inventoryArea.setItemId(itemSku.getItemId());
				inventoryArea.setItemName(itemSku.getItemName());
				inventoryArea.setUpc(itemSku.getUpc());
				inventoryArea.setColor(itemSku.getColor());
				inventoryArea.setScale(itemSku.getScale());
				inventoryArea.setSkuCode(itemSku.getSkuCode());
				inventoryArea.setSkuPic(itemSku.getSkuPic());
				inventoryArea.setWarehouseName(warehouseName);
				inventoryArea.setGmtCreate(new Date());
				inventoryArea.setGmtModify(new Date());
				
				int inventory = (Integer)itemInventoryMorphDynaBean.get("StockQty");
				int transInv = (Integer)itemInventoryMorphDynaBean.get("VirtualQty");
				int lockedInv = (Integer)itemInventoryMorphDynaBean.get("LockedQty");
				//如果占用数大于0，先用占途扣减占用，如果扣减不完的，用现货扣减
				if(lockedInv > 0) {
					transInv = transInv - lockedInv;
					if(transInv < 0) {
						inventory = inventory + transInv;
						if(inventory < 0) {
							inventory = 0;
						}
						transInv = 0;
					}
				}
				inventoryArea.setInventory(inventory);
				inventoryArea.setTransInv(transInv);
				inventoryArea.setLockedInv(0);				//由于导过来的数据没有对应占用记录，所以需要清0
				
				if(selInventoryArea != null) {
					inventoryArea.setId(selInventoryArea.getId());
					inventoryAreaMapper.updateSelectiveById(inventoryArea);
				} else {
					inventoryAreaMapper.insertSelective(inventoryArea);
				}
			}
		}
		System.out.println("===============================================库存更新数：" + jishu);
		//根据inventoryArea表更新inventory表
		inventoryMapper.updateInventoryByInventoryArea();
	}
	
	/**
	 * 获取访问1号仓的cookie
	 * 参数cookieFilePath：获取cookie保存的路径
	 */
	private BasicCookieStore getOneHaoCangCookie(String cookieFilePath) {
		BasicCookieStore cookieStore = null;
		//当不知道1hcangCookie.dat具体路径时，通过此代码查看
		//File f = new File(cookieFilePath);
		//System.out.println(f.getAbsolutePath());
		if(new File(cookieFilePath).exists()) {
			cookieStore = (BasicCookieStore)SimpleHtmlUnitUtils.readObjectFromFile(cookieFilePath);
		}
		if(cookieStore!=null && cookieStore.getCookies().size()>0) {
			String result = SimpleHtmlUnitUtils.httpRequest("http://erp.1hcang.com/ERP/Commodity/Search?page=1&start=0&limit=20", HttpMethod.GET, null, null, cookieStore, "UTF-8");
			if(result.startsWith("{\"success\":true")) {
				return cookieStore;
			}
		}
		cookieStore = new BasicCookieStore();
		String requestVerificationToken = null;
		String result = SimpleHtmlUnitUtils.httpRequest("http://erp.1hcang.com/Account/Login", HttpMethod.GET, null, null, cookieStore, "UTF-8");
		Pattern r = Pattern.compile("<input name=\"__RequestVerificationToken\" type=\"hidden\" value=\"(.*?)\" />");
		Matcher m = r.matcher(result);
		if (m.find( )) {
			requestVerificationToken = m.group(1);
		}
		Map<String, String> param = new HashMap<String, String>();
		param.put("__RequestVerificationToken", requestVerificationToken);
		param.put("CompanyKey", "9164");
		param.put("UserName", "sunny");
		param.put("Password", "123456");
		
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		headerMap.put("Accept-Encoding", "gzip, deflate");
		headerMap.put("Accept-Language", "zh-CN,zh;q=0.8");
		headerMap.put("Cache-Control", "max-age=0");
		headerMap.put("Connection", "keep-alive");
		headerMap.put("Content-Type", "application/x-www-form-urlencoded");
		headerMap.put("Host", "erp.1hcang.com");
		headerMap.put("Origin", "http://erp.1hcang.com");
		headerMap.put("Referer", "http://erp.1hcang.com/");
		headerMap.put("Upgrade-Insecure-Requests", "1");
		headerMap.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36");
		
		result = SimpleHtmlUnitUtils.httpRequest("http://erp.1hcang.com/Account/Login", HttpMethod.POST, headerMap, param, cookieStore, "UTF-8");
		SimpleHtmlUnitUtils.writeObjectToFile(cookieStore, cookieFilePath);
		return cookieStore;
	}
	
	//同步1号仓的商品信息
	@Override
	public void synItemList(String itemID) {
		//获取访问1号仓的cookie
		BasicCookieStore cookieStore = getOneHaoCangCookie("1hcangCookie.dat");
		
		//类目map
		//正式1号仓
		Map<String, Long> categoryIdMap = new HashMap<String, Long>();
		categoryIdMap.put("1fdfc406-255a-4337-9021-df5194892ab3", 46L);
		categoryIdMap.put("ff9c7c30-ec9f-472f-adf5-2ad5afe055ae", 48L);
		categoryIdMap.put("4f77525a-c430-435b-8de2-742681a7e15f", 50L);
		categoryIdMap.put("4c027ab5-dd46-4617-afc5-33d0a38659e6", 52L);
		Map<String, String> categoryNameMap = new HashMap<String, String>();
		categoryNameMap.put("1fdfc406-255a-4337-9021-df5194892ab3", "美妆护肤");
		categoryNameMap.put("ff9c7c30-ec9f-472f-adf5-2ad5afe055ae", "箱包皮具");
		categoryNameMap.put("4f77525a-c430-435b-8de2-742681a7e15f", "家庭日用");
		categoryNameMap.put("4c027ab5-dd46-4617-afc5-33d0a38659e6", "潮流服饰");
		/*
		Map<String, Long> categoryIdMap = new HashMap<String, Long>();
		categoryIdMap.put("bf20e1d3-78f6-40cd-bd49-4d08f37f5b99", 46L);
		categoryIdMap.put("14447293-0c98-4ec1-a0c9-04aa5d841aca", 48L);
		categoryIdMap.put("37cf4cc6-05e1-413a-8b27-5ef872e4ba2f", 50L);
		categoryIdMap.put("caff580d-09f4-496e-bd54-ba54f7abfa71", 52L);
		Map<String, String> categoryNameMap = new HashMap<String, String>();
		categoryNameMap.put("bf20e1d3-78f6-40cd-bd49-4d08f37f5b99", "美妆护肤");
		categoryNameMap.put("14447293-0c98-4ec1-a0c9-04aa5d841aca", "箱包皮具");
		categoryNameMap.put("37cf4cc6-05e1-413a-8b27-5ef872e4ba2f", "家庭日用");
		categoryNameMap.put("caff580d-09f4-496e-bd54-ba54f7abfa71", "潮流服饰");
		*/
		Map<String, Integer> saleTypeMap = new HashMap<String, Integer>();
		saleTypeMap.put("TOBUY", 0);
		saleTypeMap.put("STORE", 1);
		Map<String, Integer> countryMap = new HashMap<String, Integer>();
		countryMap.put("美国", 1);
		countryMap.put("德国", 2);
		countryMap.put("日本", 3);
		countryMap.put("澳洲", 4);
		Map<String, Integer> currencyMap = new HashMap<String, Integer>();
		currencyMap.put("人民币", 1);
		currencyMap.put("美元", 2);
		Map<Boolean, Integer> yesOrNoMap = new HashMap<Boolean, Integer>();
		yesOrNoMap.put(false, 0);
		yesOrNoMap.put(true, 1);
		
		System.out.println("===============================================itemID：" + itemID);
		try {
			String itemJson = SimpleHtmlUnitUtils.httpRequest("http://erp.1hcang.com/ERP/Commodity/GetItemByID?id=" + itemID, HttpMethod.GET, null, null, cookieStore, "UTF-8");
			JSONObject itemJsonObject = JSONObject.fromObject(itemJson);
			Map<String, Object> itemMap = (Map<String, Object>) JSONObject.toBean(itemJsonObject, Map.class);
			
			MorphDynaBean itemMorphDynaBean = (MorphDynaBean)itemMap.get("data");
			Item item = new Item();
			item.setName((String)itemMorphDynaBean.get("FullName"));							//商品全名
			item.setCategoryId(categoryIdMap.get((String)itemMorphDynaBean.get("TypeID")));		//类目id
			item.setCategoryName(categoryNameMap.get((String)itemMorphDynaBean.get("TypeID")));	//类目名称
			item.setItemCode((String)itemMorphDynaBean.get("SKU"));								//商品编码
			item.setSaleType(saleTypeMap.get((String)itemMorphDynaBean.get("SellType")));		//销售类型
			item.setItemShort((String)itemMorphDynaBean.get("ShortName"));						//商品简称
			item.setEnName((String)itemMorphDynaBean.get("EnglishName"));						//英文名称
			item.setBrand((String)itemMorphDynaBean.get("Brand"));								//品牌
			item.setCountry(countryMap.get((String)itemMorphDynaBean.get("CountryName")));		//国家
			item.setCurrency(currencyMap.get((String)itemMorphDynaBean.get("CurrencyName")));	//币种
			item.setBuySite((String)itemMorphDynaBean.get("WebsiteName"));						//采购站点
			item.setOrigin((String)itemMorphDynaBean.get("Origin"));							//产地
			item.setWeight((Double)itemMorphDynaBean.get("Weight"));							//重量
			item.setUnit((String)itemMorphDynaBean.get("Unit"));								//单位
			item.setSource((String)itemMorphDynaBean.get("Source"));							//来源
			item.setPromotion((String)itemMorphDynaBean.get("DiscountInfo"));					//促销信息
			item.setContactPerson((String)itemMorphDynaBean.get("Contact"));					//联系人
			item.setContactTel((String)itemMorphDynaBean.get("ContactTel"));					//联系电话
			item.setIdCard(yesOrNoMap.get((Boolean)itemMorphDynaBean.get("LogisticsType")));		//是否身份证
			item.setStartDate(DateUtil.parseDate((String)itemMorphDynaBean.get("SellStartDate")));	//销售开始日期
			item.setEndDate(DateUtil.parseDate((String)itemMorphDynaBean.get("SellEndDate")));		//销售结束日期
			item.setStatus(ItemStatus.INIT.getCode());											//1号仓商品同步到系统的初始状态
			item.setRemark((String)itemMorphDynaBean.get("Remark"));								//商品备注
			item.setSpec((String)itemMorphDynaBean.get("Spec"));									//规格
			item.setModel((String)itemMorphDynaBean.get("Model"));									//型号
			item.setDetail(((String)itemMorphDynaBean.get("Description")).replaceAll("/UploadFiles", "http://erp.1hcang.com/UploadFiles"));	//商品详情
			
			//商品主图
			List imageList = (ArrayList)itemMorphDynaBean.get("ImageList");
			StringBuffer mainPic = new StringBuffer();
			mainPic.append("{\"picList\": [");
			int mainPicNum = 1;
			for(int j=0; j<imageList.size(); j++) {
				MorphDynaBean imgM = (MorphDynaBean)imageList.get(j);
				mainPic.append("{");
				mainPic.append("\"type\": \"" + (String)imgM.get("FileType") + "\",");
				mainPic.append("\"uid\": \"i_" + j + "\",");
				mainPic.append("\"url\": \"" + "http://erp.1hcang.com" + (String)imgM.get("FolderName") + (String)imgM.get("FileID") + (String)imgM.get("FileExtension") + "\"");
				if(j == (imageList.size()-1)) {
					mainPic.append("}");
				} else {
					mainPic.append("},");
				}
				if((boolean)imgM.get("IsMainPage")) {
					mainPicNum = j+1;
				}
			}
			mainPic.append("],\"mainPicNum\": \"" + mainPicNum + "\"}");
			item.setMainPic(mainPic.toString());
			item.setGmtModify(new Date());
			
			//如果商品存在就修改，不存在就添加
			Item tjItem = new Item();
			tjItem.setItemCode(item.getItemCode());
			Item selItem = itemMapper.selectOne(tjItem);
			if(selItem != null) {
				item.setId(selItem.getId());
				item.setStatus(selItem.getStatus());
				itemMapper.updateSelectiveById(item);
				/*
				//删除底下的sku
				ItemSku delItemSku = new ItemSku();
				delItemSku.setItemCode(item.getItemCode());
				itemSkuMapper.deleteSelective(delItemSku);
				*/
			} else {
				item.setGmtCreate(new Date());
				itemMapper.insertSelective(item);
			}
			
			//增加到outer_item表
			OuterItem outerItem = new OuterItem();
			outerItem.setItemId(item.getId());
			outerItem.setPlatformType(PlatformType.YOUZAN.getCode());
			outerItem.setOneItemId(itemID);
			OuterItem selOuterItem = outerItemMapper.selectOne(outerItem);
			if(selOuterItem == null) {
				outerItem.setStatus(ItemStatus.INIT.getCode());
				outerItemMapper.insert(outerItem);
			} else {
				outerItem.setId(selOuterItem.getId());
			}
			
			//======处理sku
			String itemSkuListJson = SimpleHtmlUnitUtils.httpRequest("http://erp.1hcang.com/ERP/CommodityItem/Search?page=1&start=0&limit=200&wildcard=" + item.getItemCode(), HttpMethod.GET, null, null, cookieStore, "UTF-8");
			JSONObject itemSkuListJsonObject = JSONObject.fromObject(itemSkuListJson);
			Map<String, Object> itemSkuListMap = (Map<String, Object>) JSONObject.toBean(itemSkuListJsonObject, Map.class);
			List itemSkuList = (ArrayList)itemSkuListMap.get("data");
			for(int k=0; k<itemSkuList.size(); k++) {
				MorphDynaBean itemSkuMorphDynaBean = (MorphDynaBean)itemSkuList.get(k);
				ItemSku itemSku = new ItemSku();
				itemSku.setItemId(item.getId());
				itemSku.setItemName(item.getName());
				itemSku.setCategoryId(item.getCategoryId());
				itemSku.setCategoryName(item.getCategoryName());
				itemSku.setItemCode(item.getItemCode());
				itemSku.setSkuCode((String)itemSkuMorphDynaBean.get("SKU"));
				itemSku.setUpc((String)itemSkuMorphDynaBean.get("Barcode"));
				itemSku.setSalable(yesOrNoMap.get((Boolean)itemSkuMorphDynaBean.get("AllowSale")));
				itemSku.setColor((String)itemSkuMorphDynaBean.get("CommodityItemColor"));
				itemSku.setScale((String)itemSkuMorphDynaBean.get("CommodityItemSize"));
				itemSku.setPurchasePrice((Double)itemSkuMorphDynaBean.get("CostPrice"));
				itemSku.setFreight((long)((double)itemSkuMorphDynaBean.get("FreightPrice")*100));				//单位分
				itemSku.setSalePrice((Double)itemSkuMorphDynaBean.get("SalesPrice"));
				itemSku.setRemark((String)itemSkuMorphDynaBean.get("Remark"));
				itemSku.setGmtModify(new Date());
				itemSku.setSaleType(item.getSaleType());
				itemSku.setBrand(item.getBrand());
				itemSku.setWeight((Double)itemSkuMorphDynaBean.get("Weight"));
				
				if(itemSku.getFreight() > 0) {	//拼邮
					itemSku.setLogisticType(1);
					item.setLogisticType(1);
				} else {
					itemSku.setLogisticType(0);
				}
				
				//sku图片
				StringBuffer skuPic = new StringBuffer();
				skuPic.append("{\"picList\": [");
				skuPic.append("{");
				skuPic.append("\"type\": \"image/jpeg\",");
				skuPic.append("\"uid\": \"i_0\",");
				skuPic.append("\"url\": \"" + "http://erp.1hcang.com/UploadFiles/Resource/" + (String)itemSkuMorphDynaBean.get("MainImageUrl") + "\"");
				skuPic.append("}");
				skuPic.append("]}");
				itemSku.setSkuPic(skuPic.toString());
				
				//如果SKU存在就修改，不存在就添加
				ItemSku tjItemSku = new ItemSku();
				tjItemSku.setSkuCode(itemSku.getSkuCode());
				ItemSku selItemSku = itemSkuMapper.selectOne(tjItemSku);
				if(selItemSku != null) {
					itemSku.setId(selItemSku.getId());
					itemSkuMapper.updateSelectiveById(itemSku);
				} else {
					itemSku.setGmtCreate(new Date());
					itemSkuMapper.insert(itemSku);
				}
				//增加到outer_item_sku表
				OuterItemSku outerItemSku = new OuterItemSku();
				outerItemSku.setItemId(item.getId());
				outerItemSku.setSkuId(itemSku.getId());
				outerItemSku.setPlatformType(PlatformType.YOUZAN.getCode());
				outerItemSku.setOuterItemId(outerItem.getId());
				outerItemSku.setSkuCode(itemSku.getSkuCode());
				OuterItemSku selOuterItemSku = outerItemSkuMapper.selectOne(outerItemSku);
				if(selOuterItemSku == null) {
					outerItemSkuMapper.insert(outerItemSku);
				}
				//修改inventory表，主要修改虚拟库存
				Inventory inventory = new Inventory();
				inventory.setSkuId(itemSku.getId());
				inventory.setItemId(item.getId());
				inventory.setItemName(item.getName());
				inventory.setUpc(itemSku.getUpc());
				inventory.setSkuCode(itemSku.getSkuCode());
				Double virtualInv = (Double)itemSkuMorphDynaBean.get("StoreQty");
				if(virtualInv < 0) {
					inventory.setVirtualInv(0);
				} else {
					inventory.setVirtualInv(virtualInv.intValue());
				}
				inventory.setGmtModify(new Date());
				
				Inventory selInventory = inventoryService.queryInventoryBySkuId(itemSku.getItemId(), itemSku.getId());
				if(selInventory != null) {
					selInventory.setVirtualInv(inventory.getVirtualInv());
					inventoryMapper.updateSelectiveById(selInventory);
				} else {
					inventory.setGmtCreate(new Date());
					inventoryMapper.insert(inventory);
				}
			}
			
			//根据sku的邮费判断是否为拼邮
			if(item.getLogisticType()==null) {
				item.setLogisticType(0);	//直邮
			}
			itemMapper.updateSelectiveById(item);
		} catch(Exception e) {
			logger.error(e);
		}
	}
}
